# Generated manually for menu data initialization

from django.db import migrations


def create_initial_menu_data(apps, schema_editor):
    """创建初始菜单数据"""
    MenuItem = apps.get_model('cmdb', 'MenuItem')
    Role = apps.get_model('cmdb', 'Role')
    
    # 静态菜单路径映射（与前端config/menus.ts保持一致）
    static_menu_data = [
        ('/dashboard', '仪表盘', 'fa-dashboard'),
        ('/cmdb', 'CMDB资产管理', 'fa-server'),
        ('/cmdb/hosts', '主机管理', 'fa-server'),
        ('/cmdb/hostgroups', '主机组管理', 'fa-object-group'),
        ('/cmdb/hosttypes', '主机类型管理', 'fa-tags'),
        ('/cmdb/connections', '连接管理', 'fa-link'),
        ('/ansible', 'Ansible自动化', 'fa-cogs'),
        ('/ansible/config', '配置管理', 'fa-cog'),
        ('/ansible/inventory', '清单管理', 'fa-list'),
        ('/ansible/adhoc', '临时命令', 'fa-terminal'),
        ('/ansible/playbook', 'Playbook管理', 'fa-play'),
        ('/ansible/credentials', '凭据管理', 'fa-key'),
        ('/ansible/monitor', '监控管理', 'fa-eye'),
        ('/audit', '审计日志', 'fa-history'),
        ('/history/ssh-audit', 'SSH审计', 'fa-terminal'),
        ('/history/ansible-audit', 'Ansible审计', 'fa-cogs'),
        ('/history/sql-audit', 'SQL审计', 'fa-database'),
        ('/user', '用户管理', 'fa-users'),
        ('/cmdb/user/management', '用户管理', 'fa-user'),
        ('/cmdb/user/groups', '用户组管理', 'fa-users'),
        ('/cmdb/user/roles', '角色管理', 'fa-user-tag'),
        ('/cmdb/user/menu-permission', '菜单权限管理', 'fa-key'),
        ('/system', '系统管理', 'fa-cog'),
        ('/system/menu-management', '菜单管理', 'fa-sitemap')
    ]
    
    # 创建菜单项
    created_count = 0
    for order, (path, name, icon) in enumerate(static_menu_data, 1):
        menu_item, created = MenuItem.objects.get_or_create(
            path=path,
            defaults={
                'name': name,
                'icon': icon,
                'order': order,
                'is_enabled': True
            }
        )
        if created:
            created_count += 1
    
    print(f"✅ 菜单数据迁移完成，创建了 {created_count} 个菜单项")
    
    # 创建基础角色（如果不存在）
    super_admin_role, created = Role.objects.get_or_create(
        name='超级管理员',
        defaults={
            'description': '拥有所有权限的超级管理员角色',
            'is_system': True
        }
    )
    if created:
        print(f"✅ 创建基础角色: {super_admin_role.name}")


def reverse_menu_data(apps, schema_editor):
    """回滚菜单数据"""
    MenuItem = apps.get_model('cmdb', 'MenuItem')
    Role = apps.get_model('cmdb', 'Role')
    
    # 删除系统预设角色
    Role.objects.filter(is_system=True).delete()
    
    # 删除所有菜单项（注意：这会删除所有权限关联）
    MenuItem.objects.all().delete()
    
    print("🔄 菜单数据已回滚")


class Migration(migrations.Migration):

    dependencies = [
        ('cmdb', '0022_hostgroup_ansible_name'),
    ]

    operations = [
        migrations.RunPython(
            create_initial_menu_data,
            reverse_menu_data,
            elidable=True,
        ),
    ]
